import { animation, AnimationClip, resources, Sprite, SpriteFrame } from "cc";

//提供创建、移除、添加动画剪辑的功能
class ClipManager {
    public clips: {[name: string]: AnimationClip} = {}

    public addClip(name: string, clip: AnimationClip) {
        const oldClip = this.clips[name]
        if (oldClip) {
            console.warn('已经存在动画剪辑', oldClip)
            oldClip.decRef()
        }

        if (clip) {
            this.clips[name] = clip
            clip.addRef()
        }

        return clip
    }

    getClip(name: string) {
        const clip = this.clips[name]
        if (!clip) {
            console.warn('动画剪辑不存在:', name)
        }

        return clip
    }

    removeClip(name: string) {
        const clip = this.getClip(name)
        if (clip) {
            clip.decRef()
        }

        this.clips[name] = undefined
    }

    createTankAnimation(path: string, clipName: string) {
        if (this.clips[clipName]) {
            return this.getClip(clipName)
        }

        const spriteFrame1 = resources.get(path + '_1/spriteFrame')
        const spriteFrame2 = resources.get(path + '_2/spriteFrame')
        if (!spriteFrame1 || !spriteFrame2) {
            console.error('资源没有加载全面:', 'path:', path, spriteFrame1, spriteFrame2)
            return
        }

        const spriteFrames = [spriteFrame1, spriteFrame2]

        const animationClip = new AnimationClip()
        animationClip.duration = 0.18

        const track = new animation.ObjectTrack<SpriteFrame>()
        track.path.toHierarchy('Sprite').toComponent(Sprite).toProperty('spriteFrame')
        const curve = track.channels()[0].curve
        curve.assignSorted([
            [0.0, spriteFrames[0]],
            [0.10, spriteFrames[1]],
            [0.18, spriteFrames[0]]
        ])
        animationClip.addTrack(track)
        animationClip.wrapMode = AnimationClip.WrapMode.Loop

        return animationClip
    }
}

export const clipManager = new ClipManager()